<?php
/**
 * @author:
 * @day: 2021/6/7
 */

namespace App\Services\store;

use App\Services\BaseServices;
use App\Dao\store\StoreDao;
use App\Exceptions\ApiException as HOException;

use App\Services\system\SystemLogServices;
use Hlcreation\Services\CloudStoreServices;
use Hlcreation\Basic\Helper;
use Illuminate\Support\Facades\DB;
use App\Dao\system\SystemAdminDao;
use App\Dao\system\SystemRechargeRecordDao;


/**
 * 平台管理service
 */
class StoreServices extends BaseServices
{


    /**
     * StoreServices constructor.
     * @param StoreDao $dao
     */
    public function __construct(StoreDao $dao)
    {

        $this->dao = $dao;

    }



      /**
       * 平台列表
       */
      public function  StoreList($where=[]){
          //$level==1  副管理员   2=代理商
          $nowdate = date("Y-m-d");
          $sevendate = date("Y-m-d", strtotime(" -7 day"));
          $between =  !empty($where['create_time']) ? [$where['create_time']." 00:00:00", $where['create_time']." 23:59:59"] : [$sevendate." 00:00:00", $nowdate." 23:59:59"];
          $where['nowdate']=$nowdate;
          $where['sevendate']=$sevendate;
          $where['between']=$between;
          $field=['id','account','contacts_name','phone','un_name',
              'created_at','effective_time','message_num','shop_num','it_disabled','oem_status','cloud_status','sms_status','store_randomnum','message_usenum','sign'];
          return   $this->dao->StoreList($where,$field);


      }


      /**
       * 创建平台
       */
      public  function  StoreSave($data=[]){
          unset($data['change']);
          unset($data['date']);
          unset($data['store_id']);
          $level=$data['level'];
          if($level){
              //副管理代理商验证平台次数
              $store_list = $this->dao->getList(['creator_uid'=>$data['creator_uid']]);
              if(count($store_list)>=$data['store_num'] )throw new HOException('创建平台数量达到上限!');//代理平台数量
              $shop_sum = array_sum(array_column($store_list,'shop_num')); //管理员下所有店铺数量
              if ($shop_sum >= $data['shop_num']) throw new HOException('创建店铺数量达到上限!');
          }

          if($this->dao->count(['account'=>$data['account']])) throw new HOException('账号已存在!');
          if($this->dao->count(['un_name'=>$data['un_name']])) throw new HOException('平台已存在!');
          $data['effective_time']=empty($data['effective_time'])?0:strtotime($data['effective_time']);

          $data['created_at']=date('Y-m-d H:i:s');
          $data['halt']=Helper::createNonceStr(5);
          $data['password']=Helper::returnPwd($data['password'], $data['halt']);
          unset($data['shop_num']);
          unset($data['store_num']);
          unset($data['level']);
          DB::beginTransaction();
          try{
              $store_id=$this->dao->create($data);
              $data['uniacid_id']=$store_id;
              $data['store_randomnum']=md5($store_id.$data['halt']);
              //调用远程电子合同接口
              CloudStoreServices::CreateStore($data);
              $this->dao->update(['id'=>$store_id],['store_randomnum'=>$data['store_randomnum']]);
              //插入日志
              $LogServices = app()->make(SystemLogServices::class);
              $LogServices->SaveLog($data['creator_uid'],'创建平台','平台名称:'.$data['un_name'].'--账号:'.$data['account']);

           DB::commit();
           return true;
        } catch(\Exception $exception) {
            DB::rollBack();
            throw new HOException($exception->getMessage());

        }
      }


      /**
       * 修改平台
       */
      public  function  StoreEdit($id='',$data=[]){
          unset($data['date']);
          unset($data['change']);
          if(empty($id))  throw new HOException('平台不存在');
          if($this->dao->IsStore(['account'=>$data['account']],$id)) throw new HOException('账号已存在!');
          if($this->dao->IsStore(['un_name'=>$data['un_name']],$id)) throw new HOException('平台已存在!');
          $data['effective_time']=empty($data['effective_time'])?0:strtotime($data['effective_time']);
          if ($data['password']){
              $data['halt']=Helper::createNonceStr(5);
              $data['password']=Helper::returnPwd($data['password'], $data['halt']);
          }
          unset($data['store_id']);
          $data['updated_at']=date('Y-m-d H:i:s');
          $admin_id=$data['creator_uid'];
          unset($data['creator_uid']);
          unset($data['level']);
          DB::beginTransaction();
          try{
               $this->dao->update(['id'=>$id],$data);
               //调用远程电子合同接口
               $data['uniacid_id']=$id;
               CloudStoreServices::UpdateStore($data);
              //插入日志
              $LogServices = app()->make(SystemLogServices::class);
              $LogServices->SaveLog($admin_id,'修改平台','平台id:'.$id.'--账号:'.$data['account'].'--平台名称:'.$data['un_name']);

              DB::commit();
              return true;
         } catch(\Exception $exception) {
            DB::rollBack();
            throw new HOException($exception->getMessage());

        }

        }


      /**
       * 获取平台信息
       */
      public  function  getInfo($id=''){

          if(empty($id))  throw new HOException('平台不存在');

          $field=['id','account','contacts_name','phone','un_name',
              'created_at','effective_time','message_num','shop_num'];
          return  $this->dao->getOne(['id'=>$id],$field);
      }


      /**
       * 软删除
       */
      public  function  StoreDel($id='',$admin_id=''){
          if(empty($id))  throw new HOException('平台不存在');

          $data['deleted_at']=date('Y-m-d H:i:s');
          DB::beginTransaction();
          try{
              $this->dao->delete(['id'=>$id]);
              //调用电子合同接口
              CloudStoreServices::DelStore(['uniacid_id'=>$id]);
              //插入日志
              $LogServices = app()->make(SystemLogServices::class);
              $LogServices->SaveLog($admin_id,'删除平台','平台id为'.$id);
             DB::commit();
              return true;
         } catch(\Exception $exception) {
            DB::rollBack();
            throw new HOException($exception->getMessage());

        }

      }


      /**
       * 禁用平台
       */
      public  function  EditDisabled($admin_id,$id,$type){
          if(empty($id))  throw new HOException('平台不存在');

          $data['updated_at']=date('Y-m-d H:i:s');
          DB::beginTransaction();
          try{
              $this->dao->update(['id'=>$id],['it_disabled'=>$type]);
              //调用电子合同接口
              CloudStoreServices::DisabledStore(['uniacid_id'=>$id,'it_disabled'=>$type]);
              //插入日志
              $LogServices = app()->make(SystemLogServices::class);
              $type=empty($type)?'关闭禁用平台操作':'开启禁用平台操作';
              $LogServices->SaveLog($admin_id,'禁用平台','平台id:'.$id.'--'.$type);

             DB::commit();
              return true;
         } catch(\Exception $exception) {
            DB::rollBack();
            throw new HOException($exception->getMessage());

        }


      }


      /**
       * 平台列表
       * */
      public function un_list(){
          return $this->dao->getList([],['id','un_name']);
      }


      /**
       * 平台配置开关
       */
      public function  storeConfig($admin_id,$type,$id,$status){
          if(empty($id))  throw new HOException('平台不存在');

          switch ($type) {
           case 1:
              return $this->HandleConfigData($admin_id,$id,$status,'oem_status');
              break;

              case 2:
                  return $this->HandleConfigData($admin_id,$id,$status,'cloud_status');
                  break;

                  case 3:
//                      if($status==1 && $sign=='')  throw new HOException('请输入短信签名');
                      return $this->HandleConfigData($admin_id,$id,$status,'sms_status');
                      break;
          }


      }

      /**
       * 平台配置开关数据处理
       * @param unknown $admin_id
       * @param unknown $id
       * @param unknown $status
       * @throws HOException
       */
      private function  HandleConfigData($admin_id,$id,$status,$type){

          DB::beginTransaction();
          try{
            $this->dao->update(['id'=>$id],[$type=>$status]);
            //调用电子合同接口
            CloudStoreServices::ConfigStore(['uniacid_id'=>$id,$type=>$status]);
              //插入日志
              $LogServices = app()->make(SystemLogServices::class);
              $type_status=empty($status)?'关闭'.$type.'配置':'开启'.$type.'配置';
              $LogServices->SaveLog($admin_id,'平台配置开关','平台id:'.$id.'--'.$type_status);

              DB::commit();
              return true;
              } catch(\Exception $exception) {
                  DB::rollBack();
                  throw new HOException($exception->getMessage());

              }
      }


      /**
       * 进入平台
       */
      public  function  entryContract($store_id=''){
          //调用电子合同接口
          $store=$this->dao->getOne(['id'=>$store_id],['store_randomnum']);
          if(empty($store))  throw new HOException('平台不存在');
          return CloudStoreServices::EntryContract(['store_randomnum'=>$store['store_randomnum']]);
      }


      /**
       * 同步合同短信次数
       */
      public function  synchroSmsContract($store_id=''){

              //调用电子合同接口
              if(empty($store_id))  throw new HOException('平台不存在');
              $data=CloudStoreServices::synchroSmsContract(['uniacid_id'=>$store_id]);

              if($data){
                  if(!isset($data['data'])) throw new HOException('电子合同参数有误 请联系客服');
                  $this->dao->update(['id'=>$store_id],[
                          'message_num'=>$data['data']['message_num'],
                          'message_usenum'=>$data['data']['message_usenum'],
                          'shop_num' => $data['data']['shop_num'],
                          'shop_usenum' => $data['data']['shop_usenum']
                      ]
                      );
                  return true;
              }else{
                   throw new HOException('电子合同参数有误 请联系客服');
              }

      }



      /**
       * 修改合同次数短信次数
       * @param unknown $arr
       * @param unknown $store_id
       * @param unknown $admin_id
       * @throws HOException
       */
      public function  setSmsContract($arr,$store_id,$admin_id){

          DB::beginTransaction();
          try{
              //先同步电子合同系统短信次数合同次数
              $this->synchroSmsContract($store_id);
              $platform=$this->dao->getOne(['id'=>$store_id]);
              if ($arr['message_num'] < $platform['message_usenum']) throw new HOException('设置的短信次数不能小于已使用次数');
              if ($arr['shop_num'] < $platform['shop_usenum']) throw new HOException('设置的店铺个数不能小于已创建店铺数');
              $AdminServices = app()->make(SystemAdminDao::class);
              $admin = $AdminServices->getOne(['id' => $platform['creator_uid']],['id','level','sms_num','shop_num']);
              $admin_platform = $this->dao->getList(['creator_uid' => $platform['creator_uid']]);
              $message_sum = array_sum(array_column($admin_platform,'message_num')); //管理员已创建短信总数
              $shop_sum = array_sum(array_column($admin_platform,'shop_num')); //管理员已创建店铺总数
              $message_inc = $arr['message_num'] - $platform['message_num']; //增加了多少短信
              $shop_inc = $arr['shop_num'] - $platform['shop_num']; //增加了多少店铺
              $message_num = $message_sum + $message_inc; //添加后得短信总数
              $shop_num = $shop_sum + $shop_inc; //添加后得店铺总数
              if ($message_num > $admin['sms_num'] && $admin['level']) {
                  //使用量超过拥有数量且非超管
                  throw new HOException('管理员可创建'.$admin['sms_num'].'条短信，已创建'.$message_num.'条，请充值短信次数');
              }else{
                  $this->operation_record($admin_id,$store_id,1,$platform['message_num'],$arr['message_num']);
              }
              if ($shop_num > $admin['shop_num'] && $admin['level']){
                  throw new HOException('管理员可创建'.$admin['shop_num'].'个店铺，已创建'.$shop_num.'个，请充值店铺个数');
              }else{
                  $this->operation_record($admin_id,$store_id,2,$platform['shop_num'],$arr['shop_num']);
              }
              $this->dao->update(['id'=>$store_id],['message_num'=>$arr['message_num'],'shop_num'=>$arr['shop_num']]);
              $data=[
                  'message_num'=>$arr['message_num'],
                  'shop_num'=>$arr['shop_num'],
                  'uniacid_id'=>$store_id
              ];
              CloudStoreServices::setSmsContract($data);
              //插入日志
              $LogServices = app()->make(SystemLogServices::class);
              $LogServices->SaveLog($admin_id,'修改短信次数店铺次数','平台ID:'.$store_id.'--账号ID:'.$admin['id'].'--上次剩余短信次数:'.$platform['message_num'].'本次修改为:'.$arr['message_num'].'--上次店铺个数:'.$platform['shop_num'].'本次修改为:'.$arr['shop_num']);
              DB::commit();
              return true;
          } catch(\Exception $exception) {
              DB::rollBack();
              throw new HOException($exception->getMessage());
          }
      }


      /**
       * 修改平台新增操作记录
       */
      private function  operation_record($admin_id,$store_id,$type,$balance,$second_number){
          //操作短信店铺次数记录
          $SystemRechargeServices = app()->make(SystemRechargeRecordDao::class);
          if (!$SystemRechargeServices->create([
              'creator_uid'=>$admin_id,
              'store_id'=>$store_id,
              'type'=>$type,
              'balance'=>$balance,
              'second_number'=>$second_number
          ])) throw new HOException('平台次数记录失败');
      }



}
